package dk.statsbiblioteket.subtitleProject.subtitleStream;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dk.statsbiblioteket.subtitleProject.SubtitleProject;
import dk.statsbiblioteket.subtitleProject.common.OCR;
import dk.statsbiblioteket.subtitleProject.common.ResourceLinks;
import dk.statsbiblioteket.subtitleProject.common.SubtitleFragment;
import dk.statsbiblioteket.util.console.ProcessRunner;

/**
 * Class to operate on .son file generated by projectX
 */
public class SONHandler {
	@SuppressWarnings("unused")
	private static Logger log = LoggerFactory.getLogger(SubtitleProject.class);
	/**
	 * Iterates through .SON subtitlefile, and generates subtitleFragments based on loginfo and ocr result 
	 * @param sonFiles to parse
	 * @param properties
	 * @return Map with subtitleFramgnets with pid as key
	 * @throws IOException if .sonfile don't exists
	 */
	public static Map<String, List<SubtitleFragment>> sonHandler(Map<String, File> sonFiles, ResourceLinks resources) throws IOException{
		Map<String, List<SubtitleFragment>> subsToPids = new HashMap<String, List<SubtitleFragment>>();
		Iterator<String> it = sonFiles.keySet().iterator();
		while(it.hasNext()){
			String currentPid = it.next();
			try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(sonFiles.get(currentPid)), "UTF-8"))){
				String line;
				List<SubtitleFragment> subtitleFragments = new ArrayList<SubtitleFragment>();
				while ((line = reader.readLine()) != null)
				{
					if(line.contains("Display_Area")){
						line = reader.readLine();
						String[] temp = line.split("\t");
						int no = Integer.parseInt(temp[0]);
						String[] timeStamp1 = temp[2].split(":");
						String[] timeStamp2 = temp[3].split(":");
						String timeStamp = timeStamp1[0]+":"+timeStamp1[1]+":"+timeStamp1[2]+","+timeStamp1[3]+"0 --> "+timeStamp2[0]+":"+timeStamp2[1]+":"+timeStamp2[2]+","+timeStamp2[3]+"0";
						File bmpFile = new File(resources.getOutput()+temp[4]);
						String pngFileName = bmpFile.getAbsolutePath().replaceFirst("\\.bmp$", ".png");
						String commandline = resources.getConvert()+" "+bmpFile.getAbsolutePath() + " "+ pngFileName;
						//log.debug("Running commandline: {}",commandline);
						ProcessRunner pr = new ProcessRunner("bash","-c",commandline);
						pr.run();
						if (pr.getReturnCode() != 0){
							throw new IOException("Failed to run '"+commandline+"', got '"+pr.getProcessErrorAsString());
						}
						bmpFile.delete();
						subtitleFragments.add(OCR.ocrFrameSon(new File(pngFileName), resources, timeStamp, no));
					}
				}
				subsToPids.put(currentPid, subtitleFragments);
			}
		}
		return subsToPids;
	}
}